<?php
class HomesController extends AppController {
	public $name = 'Homes';
	public $uses=array('Task','Type','Priority','User','Status','Project','TaskNotification','ProjectUser','Menu','Field','FieldValue','Comment','FileAttach','FileManager');
	
	public $components=array('Email');
	public $layout='admin_default';

	function admin_index(){		
		if(empty($this->user['id'])){
			$this->layout=null;
			$this->render('admin_index1');
		}
		else $this->render('admin_index');
	}

	function admin_home(){	
		$this->Session->write('CurrentModule','Home');
		//get filter field
		$filterField=array(
		'Task.name'=>_resource('task name',true),
		'Task.description'=>_resource('task description',true),
		'Task.code'=>_resource('task code',true),
		'Project.name'=>_resource('project name',true)
		);
		//get status
		$this->set("statuses",$this->Status->find('list'));
		//default status
		if(!$this->Session->check('Home.status_id')){			 
			//get default status
			$status=$this->Status->find('first',array('conditions'=>array('default'=>1)));
			if(!empty($status))$this->Session->write('Home.status_id',$status['Status']['id']);
		}
		
		$this->set('filterField',$filterField);
		$this->render('admin_home','ajax');
	}

	function admin_lists(){
		$this->Session->write('CurrentModule','Home');
		$user=$this->Auth->user();
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check('Home.limit')){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>'Task.id desc',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'status_id'=>$this->Session->read('Home.status_id')
			
			);
			//luu vao session
			$this->Session->write('Home',$tmp);
		}

		
		
		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		$this->Task->locale=$this->Session->read('adminLang');
		//===================================================================

		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...
		$paginate=$this->Session->read('Home');	
		
		if($this->Session->check('Home.status_id')){
			$paginate['conditions']['Status.id']=$this->Session->read('Home.status_id');
			//get status hidden on project
			$statusNotHidden=$this->Status->find('list',array('fields'=>array('Status.id','Status.id'),'conditions'=>array('Status.published'=>1)));
			$paginate['conditions']['Project.status_id']=$statusNotHidden;
		}
	
		

		//get all project by user
		if(!Configure::read('Session.isSa') && !Configure::read('Session.isAdmin') ){
			$projectjoins=$this->ProjectUser->find('list',array('fields'=>array('ProjectUser.project_id','ProjectUser.project_id'),'conditions'=>array('ProjectUser.user_id'=>$user['id'])));
			$paginate['conditions']['Task.project_id']=$projectjoins;
		}
			
		//get all notify by this user
		$notify=$this->TaskNotification->getAllByUser($user['id']);
		$nonotify=$this->TaskNotification->getAllNonByUser($user['id']);
		$this->set('notify',$notify);
		//check if is notify, get all notify first, default is get notify first.
		if(!isset($this->paginate['isNotifySort'])){
			$paginate['isNotifySort']=1;
			
		}
		
		if($paginate['isNotifySort']){
			$data0=array();
			$this->params['paging']['Home']=$paginate;			
			$limit=$paginate['limit'];
			$pageCount=1;
			$count=0;
			$currentPage=$paginate['page'];
			
			//query
			//get all count:
			$paginate['conditions']['Task.id']=$notify;			
			$countNotify=$this->Task->find('count',array('conditions'=>$paginate['conditions']));
			$paginate['conditions']['Task.id']=$nonotify;
			$countNoNotify=$this->Task->find('count',array('conditions'=>$paginate['conditions']));
			$count=$countNoNotify+$countNotify;
			$pageCount=ceil($count/$limit);
			unset($paginate['page']);
			//get notify by page
			//check if current page is include notify
			if($countNotify>($currentPage-1)* $limit){
				//get <limit> notify record
				$paginate['conditions']['Task.id']=$notify;
				$paginate['limit']=(($currentPage-1)* $limit).','.$limit;
				
				$data0=$this->Task->find('all',$paginate);
				//check if is equal <limit>:
				$lack=$limit-count($data0);
				if($lack>0){
					//get lack record (no notify record)
					$paginate['conditions']['Task.id']=$nonotify;
					$paginate['limit']=$lack;
					foreach($this->Task->find('all',$paginate) as $k=>$v)$data0[]=$v;
				}				
			}
			else{
				$paginate['conditions']['Task.id']=$nonotify;
				$start=($currentPage-1)*$limit-$countNotify;							
				$paginate['limit']=$start.','.$limit;
				$data0=$this->Task->find('all',$paginate);
			}
			$this->params->params['paging']['Home']['limit']=$limit;
			$this->params->params['paging']['Home']['page']=$currentPage;
			$this->params->params['paging']['Home']['pageCount']=$pageCount;
			$this->params->params['paging']['Home']['count']=$count;
			//t($this->params);
		}
		else{
			//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
			//lay data da duoc phan trang va truyen vao bien $data0		
			$this->paginate=$paginate;
			$data0=$this->paginate('Home');
		}
		
		$this->paginate=$paginate;
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);

		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website.
		$this->render('admin_lists','ajax');
	}

	

	function admin_edit($id=null,$locale=null){
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		$this->Task->locale=$locale;
		$name_error=_resource('can not be null',true);
		$isInsert=false;
		$id=intval($id);
		
		$task=$this->Task->read(null,$id);
		//get project
		$proj=$this->Project->find('first',array('conditions'=>array('Project.id'=>$task['Task']['project_id'])));
		//check if task is belong to project			
		if(empty($task) || $task[$this->uses[0]]['project_id']!=$proj['Project']['id']){
			$this->Session->write('error',_resource('can not find data',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		//check if user is assignee or manager
		$user=$this->Auth->user();		
		if(!Configure::write('Session.isSa') && !Configure::write('Session.isAdmin') && !$this->Session->read('isManager')&& !$this->Session->read('isAssignee')){
			$this->Session->write('error',_resource('You have not permission',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		
		
		
		if(!empty($this->data)){	
			$data=$this->data;
			if($this->Task->validates($data)){
				if($this->Task->save($data)) {
					
					//update fields
					if(isset($data['Field'])){
						//t($data['Field']);
						foreach($data['Field'] as $k=>$v){
							$v['task_id']=$id;
							App::import('Model','FieldValue');
							$FieldValue =& new FieldValue();
							//$Field->create($data);
							$FieldValue->save($v);
						}
					}
					
				//update file
					//get old file					
					$oldfile=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
					//convert to id=>array
					if(!empty($oldfile)){
						foreach($oldfile as $k=>$v){
							$oldfileConverted[$v['FileAttach']['id']]=$v;
						}
					}
					//check new file
					$updateMsg='';
					if(isset($data['FileAttach'])){
						//t($data['Field']);
						$updateMsg='Add new files:<br />';
						foreach($data['FileAttach'] as $k=>$v){
							if(!empty($v['id']) && !isset($oldfileConverted[$v['id']])){
								$insertdata['user_id']=$user['id'];
								$insertdata['file_id']=$v['id'];
								$insertdata['task_id']=$data[$this->uses[0]]['id'];		
								$this->FileAttach->create($insertdata);
								$this->FileAttach->save();
								//mount to file
								$this->FileManager->updateAll(array('mount'=>'mount + 1'),array('id'=>$v['id']));
								$updateMsg.=$data['FileAttach']['name'];
							}
							else{
								//file not change, remove in oldfileConvert list
								unset($oldfileConverted[$v['id']]);
							}
						}
					}
					//delete old file
					if(!empty($oldfileConverted)){
						$updateMsg.='Delete files:<br />';
						foreach($oldfileConverted as $k=>$v){
							$this->FileAttach->deleteAll(array('FileAttach.id'=>$k),false);
							//unmount
							$this->FileManager->updateAll(array('mount'=>'mount - 1'),array('id'=>$v['FileManager']['id']));
							$updateMsg.=$v['FileManager']['name'];							
						}
					}
					
					//add watch
					//add watch owner
					$this->TaskNotification->addWatch($this->user['id'],$this->data[$this->uses[0]]['id']);
					if(isset($data[$this->uses[0]]['watches'])){
						foreach($data[$this->uses[0]]['watches'] as $k=>$v){
							$this->TaskNotification->addWatch($v,$this->data[$this->uses[0]]['id']);
						}
					}
					
					//addnotify
					//addnotify for oldassignee
					if(isset($data[$this->uses[0]]['assignees'])){
						$this->TaskNotification->addNotify($this->data['Task']['assignees'],$this->data[$this->uses[0]]['id']);
						$this->TaskNotification->notifyToUserId($this->data[$this->uses[0]]['assignees'],$this->data[$this->uses[0]]['id']);	
					}
					
					//remove notify for oldassignee
					$this->TaskNotification->removeNotify($task[$this->uses[0]]['assignees'],$this->data[$this->uses[0]]['id']);
					
					if(!empty($updateMsg)){
						$updateMsg='<b>Task update:</b><br/>'.$updateMsg;
						$this->Comment->addComment($updateMsg,$this->user['id'],$data['FileAttach']['task_id']);
					}
					
					$this->Session->write('message',_resource('update data successful',true));
					$this->redirectAjaxTo('homes/home','mainContent');
					
						
					$this->data=null;					
					$isInsert=true;
					
					

				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{			
			
			
			//get all field
			if(!empty($proj['Project']['fields'])){
				App::import('Model','Field');
				$Field =& new Field();
				$option['joins']=array(
					array('table'=>'field_values',
						'type'=>'left',
						'alias'=>'FieldValue',
						'conditions'=>array('task_id'=>$id,
							'Field.id=FieldValue.field_id'
						)
					)	
				);
				$option['fields']=array('Field.id','Field.name','Field.value','Field.fieldvalue_id');
				$option['conditions']=array('Field.id'=>explode(',', $proj['Project']['fields']));
				
				$Field->virtualFields=array('value'=>'FieldValue.value','fieldvalue_id'=>'FieldValue.id');
				$fields=$Field->find('all',$option);			
				if(count($fields)>0){
					foreach($fields as $k=>$v){
						$task['Field'][$v['Field']['id']]=array('id'=>$v['Field']['fieldvalue_id'],'field_id'=>$v['Field']['id'],'name'=>$v['Field']['name'],'value'=>$v['Field']['value']);
					}
				}				
				
			}
		//get all file attach
			$fileattach=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
			if(!empty($fileattach)){
				foreach($fileattach as $k=>$v){
					$fileitem['id']=$v['FileAttach']['id'];
					$fileitem['name']=$v['FileManager']['name'];
					if($v['User']['username']!=$user['username'])
						$fileitem['username']=$v['User']['username'];
					$task['FileAttach'][]=$fileitem;		
				}
			}
			
			$this->data=$task;
		}

			$types=$this->Type->find('list',array('order'=>'view_order desc'));
			$this->set('types',$types);
			//get all status		
			$statuses=$this->Status->find('list',array('order'=>'view_order desc'));
			$this->set('statuses',$statuses);
			//get all prior		
			$priors=$this->Priority->find('list',array('order'=>'view_order desc'));
			$this->set('priors',$priors);
			//get all Project
			$projects=$this->Project->find('list');
			$this->set('projects',$projects);
			
			//get all user in current project
			if(isset($proj['Project']['users']) && !empty($proj['Project']['users']))
			{
				$users=$this->User->getUserByArrayUserId(explode(',',$proj['Project']['users']));
				$this->set('users',$users);
			}
		

		
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
		$this->render('admin_edit','ajax');
	}

function admin_detail($id=0){
		
		$id=intval($id);
		
		if($id==0){
			$id=intval($this->Session->read('Home.id'));
		}
		if($id!=0){
			$user=$this->user;
			//unnotify
			$this->TaskNotification->unnotify($user['id'],$id);
			
			$this->Session->write('Home.id',$id);
			
			
			
			$task=$this->Task->read(null,$id);
			if(empty($task)){
				$this->Session->write('error',_resource('can not find data',true));
				$this->redirectAjaxTo('homes/dashboard','listContent');
			}
			
			$pid=$task['Task']['project_id'];				
			$proj=$this->Project->read(null,$pid);
			
			if(empty($proj)){
				$this->Session->write('error',_resource('can not find data',true));
				$this->redirectAjaxTo('homes/dashboard','listContent');
			}
			
			//check userjoin
			$user=$this->user;
			$userjoin=$this->ProjectUser->find('first',array('conditions'=>array('project_id'=>$pid,'ProjectUser.user_id'=>$user['id'])));
			if(empty($userjoin) && $user['group_id']!=4 && $user['group_id']!=1 ){
				$this->Session->write('error',_resource('can not find data',true));
				$this->redirectAjaxTo('projects','mainContent',true);
			}
			
			//check assignee			
			if($task['Task']['assignees']==$user['id'])Configure::write('Session.isAssignee',true);		
						
			
			//check is manager		
			if($user['id']==$proj['Project']['manager'])Configure::write('Session.isManager',true);
			
			//check is qa
			if(strpos($proj['Project']['qa'],','.$user['id'].',') 
			|| $proj['Project']['qa']==$user['id']
			|| substr($proj['Project']['qa'],0,strlen($user['id'])+1)==$user['id'].','
			|| (strlen($proj['Project']['qa'])>strlen($user['id']) && substr($proj['Project']['qa'],strlen($proj['Project']['qa'])-strlen($user['id'])-1)==','.$user['id']))
				Configure::write('Session.isQA',true);
				
			//check is owner
			if($user['id']==$task['Task']['user_id'])Configure::write('Session.isOwner',true);
			
			//get all attach file
			//get all file attach
			$fileattach=$this->FileAttach->find('all',array('conditions'=>'task_id='.$task['Task']['id']));
			$task['FileAttach']=$fileattach;
			
			$this->set('data',$task);
			unset($option);
			
			//get all field
			if(!empty($proj['Project']['fields'])){
				$option['joins']=array(
					array('table'=>'field_values',
						'type'=>'left',
						'alias'=>'FieldValue',
						'conditions'=>array('task_id'=>$id,
							'Field.id=FieldValue.field_id'
						)
					)	
				);
				$option['fields']=array('FieldValue.id','Field.id','Field.name','Field.value');
				if(!empty($proj['Project']['fields']))$option['conditions']=array('Field.id'=>explode(',', $proj['Project']['fields']));			
				$this->Field->virtualFields=array('value'=>'FieldValue.value');
				$fields=$this->Field->find('all',$option);
				$this->set('fields',$fields);	
			}	

			//get all status		
			$statuses=$this->Status->find('list',array('order'=>'view_order desc'));
			$this->set('statuses',$statuses);
			$this->set('proj',$proj);
			
			//get all user in current project
			if(isset($proj['Project']['users']) && !empty($proj['Project']['users']))
			{
				$users=$this->User->getUserByArrayUserId(explode(',',$proj['Project']['users']));
				$this->set('users',$users);
			}
		}
		else{
			$this->Session->write('error',_resource('can not find data',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}	
		
		$this->render('admin_detail','ajax');
	}
	
	
	function admin_changeStatus($id=0){
		
		if(empty($this->data)){	
			exit;
		}
		
		$tid=$id=intval($id);
		
		
		
		
		//check if task is belong to project
		$task=$this->{$this->uses[0]}->read(null,$tid);			
		if(empty($task)){
			$this->Session->write('error',_resource('can not find data',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		
		$pid=$task['Task']['project_id'];
		$proj=null;
		$proj=$this->Project->read(null,$pid);
		if(empty($proj)){
			$this->Session->write('error',_resource('can not find data',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		
		//check userjoin
		$user=$this->user;
		$userjoin=$this->ProjectUser->find('first',array('conditions'=>array('project_id'=>$pid,'ProjectUser.user_id'=>$user['id'])));
		if(empty($userjoin) && $user['group_id']!=4 && $user['group_id']!=1 ){
			$this->Session->write('error',_resource('can not find data',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		
		//check assignee			
		if($task['Task']['assignees']==$user['id'])Configure::write('Session.isAssignee',true);		
					
		
		//check is manager		
		if($user['id']==$proj['Project']['manager'])Configure::write('Session.isManager',true);
		
		//check is qa
		if(strpos($proj['Project']['qa'],','.$user['id'].',') 
		|| $proj['Project']['qa']==$user['id']
		|| substr($proj['Project']['qa'],0,strlen($user['id'])+1)==$user['id'].','
		|| (strlen($proj['Project']['qa'])>strlen($user['id']) && substr($proj['Project']['qa'],strlen($proj['Project']['qa'])-strlen($user['id'])-1)==','.$user['id']))
			Configure::write('Session.isQA',true);
			
		//check is owner
		if($user['id']==$task['Task']['user_id'])Configure::write('Session.isOwner',true);
		
		
		//check if user is manager or assignee
		if(!Configure::read('Session.isSa') && !Configure::read('Session.isAdmin') && !Configure::read('Session.isManager')&& !Configure::read('Session.isQA')&& !Configure::read('Session.isOwner') && !Configure::read('Session.isAssignee')){
			$this->Session->write('error',_resource('You have not permission',true));
			$this->redirectAjaxTo('homes/home','mainContent');
		}
		//t($this->data);
		//update progress:
		$updateMsg='';
		$updatedata=array();
		//status
		if($this->data['Task']['status_id']!=$this->data['Task']['oldstatus_id']){
			$updatedata['status_id']=$this->data['Task']['status_id'];
			$listStatus=$this->Status->find('list',array('fields'=>'id,name'));
			$updateMsg='Status: '.$listStatus[$this->data['Task']['oldstatus_id']].' ==> '.$listStatus[$this->data['Task']['status_id']].'<br />';
			$updateMsg='<b>Task update:</b><br/>'.$updateMsg;	
			$this->Comment->addComment($updateMsg,$user['id'],$tid,false);	
			$updateMsg='';	
		}
		
		//assignee
		if(isset($this->data['Task']['assignees']) && $this->data['Task']['assignees']!=$task['Task']['assignees']){
			$updatedata['assignees']=$this->data['Task']['assignees'];
			//addwatch for oldassignee
			$this->TaskNotification->addNotify($this->data['Task']['assignees'],$task['Task']['id']);
			//remove watch for oldassignee
			$this->TaskNotification->removeNotify($task[$this->uses[0]]['assignees'],$task['Task']['id']);
			$listUser=$this->User->find('list',array('fields'=>'id,username','conditions'=>'id ='.$this->data['Task']['assignees']));			
			$updateMsg.='Assign to: '.$listUser[$this->data['Task']['assignees']].'<br />';
			$this->TaskNotification->addNotify($this->data['Task']['assignees'],$taskid);			
		}
		//fields
		if(isset($this->data['Field'])){			
			foreach($this->data['Field'] as $k=>$v){
				if($v['value']!=$v['oldvalue']){	
					if(!empty($v['fieldvalue_id'])){
						$this->FieldValue->updateAll(array('value'=>'\''.$v['value'].'\''),array('id'=>$v['fieldvalue_id']));
					}
					else{
						$fielddata['value']=$v['value'];
						$fielddata['field_id']=$v['field_id'];
						$fielddata['task_id']=$tid;
						$this->FieldValue->create($fielddata);
						$this->FieldValue->save();
					}
					$updateMsg.=$k.': '.$v['value'].'<br />';
				}				
			}
		}
		
		//update task
		if(!empty($updatedata))$this->Task->updateAll($updatedata,array('Task.id'=>$tid));
		//add comment
		if(!empty($updateMsg)){
			$updateMsg='<b>Task update:</b><br/>'.$updateMsg;
			$this->Comment->addComment($updateMsg,$user['id'],$tid);
			$this->Session->write('message',_resource('Task was updated',true));
			//$this->redirectAjaxTo('homes/home','mainContent');
		}
		
		$this->admin_lists();
	}
	

	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write('Home.sortField',$sortField);
			$this->Session->write('Home.sortDir',$sortDir);
			$this->Session->write('Home.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}

	function admin_page($page=1){
		$this->Session->write('Home.page',$page);
		$this->admin_lists();
	}

	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write('Home.limit',$limit);
		}
		$this->admin_lists();
	}

function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write('Home.filterText',$this->request->data['filter_text']);
			$this->Session->write('Home.filterField',$this->request->data['filter_field']);
			//$conditions=$this->Session->read('Home.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';
				$this->Session->write('Home.page',1);				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			
			$this->Session->write('Home.conditions',$conditions);
		}
		$this->admin_lists();
	}
	
	function admin_status($statusid=0){
		//status
		$statusid=intval($statusid);
		if($statusid)$this->Session->write('Home.status_id',$statusid);
		else $this->Session->delete('Home.status_id');
		$this->Session->write('Home.page',1);
		$this->admin_lists();
	}
	/*
	 * ham dung de save thu tu cua tung mau tin
	 */
	function admin_save(){
		if(isset($this->params['form']['order'])){
			foreach($this->params['form']['order'] as $k=>$v){
				if(intval($v)){
					//set view order for category
					$this->Task->updateAll(array('Home.view_order'=>intval($v)),array('Home.id'=>$k));
				}
			}
		}
		$this->Session->write('message',_resource('view order has been update',true));
		$this->admin_lists();
	}

	/*
	 * ham dung khi co su dung chuc nang da ngon ngu
	 * dung de change locale cua he thong
	 * tham so truyen vao la locale cua ngon ngu
	 */
	function admin_changeLocale($locale=null){
		//luu session
		if($locale){
			$this->Session->write('adminLang',$locale);
		}
		//reload lai luoi de apply locale vua change
		$this->admin_lists();
	}

	
	function admin_selCat($id=null) {
		//kiem tra neu submit tu form
		//luu dieu kien chon
		$conditions=null;
		$conditions=$this->Session->read('Home.conditions');
		$conditions['Home.'.$this->Task->belongsTo[$this->uses[1]]['foreignKey']]=intval($id);
		if($id!=null){
			//luu sesssion de giu lai gia da chon
			$this->Session->write('Home.catid',intval($id));
		}
		else{
			$this->Session->write('Home.catid','');
			unset($conditions['Home.'.$this->Task->belongsTo[$this->uses[1]]['foreignKey']]);
		}
		$this->Session->write('Home.conditions',$conditions);
		$this->admin_index();
	}
	
	//==========================function for frontend===========================================
	
	function index(){	
		$this->layout=null;	
		$this->render('index');
	}
	

//===============other function====================
	


}
?>
